package com.jd.platform.gobrs.client.handler;

import com.jd.platform.gobrs.client.handler.auto.AutoCache;
import com.jd.platform.gobrs.client.handler.manual.ManualCache;
import com.jd.platform.gobrs.common.enums.CacheHandlerEnums;
import com.jd.platform.gobrs.common.exception.CacheHandlerNotFoundException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: gobrs
 * @ClassName CacheHanderFactory
 * @description:
 * @author: sizegang
 * @create: 2022-01-08 16:53
 * @Version 1.0
 **/
public class CacheHandlerFactory {

    private static Map<Integer, CacheHandler> cacheHandler = new ConcurrentHashMap<>();

    public static CacheHandler getInstance(Integer key) {
        if (cacheHandler.get(key) == null) {
            synchronized (CacheHandlerFactory.class) {
                if (cacheHandler.get(key) == null) {
                    if (key.equals(CacheHandlerEnums.AUTO_CACHE.getType())) {
                        AutoCache autoCache = new AutoCache();
                        cacheHandler.put(key, autoCache);
                        return autoCache;
                    }
                    if (key.equals(CacheHandlerEnums.MANUAL_CACHE.getType())) {
                        ManualCache manualCache = new ManualCache();
                        cacheHandler.put(key, manualCache);
                        return manualCache;
                    }
                    throw new CacheHandlerNotFoundException("cache handler not found !");
                }
            }
        }
        return cacheHandler.get(key);
    }

}
